import {
    getMachTypes, getModelList, getMachList, addMach, updateMach, delMach,
    getMachParams, getMachParamInfo, 
    getMachEffInfo,
    getMachSimulutionInfo,
    getCustomDate
} from '../services/machService';


const initialState = {
    currentPage:1,
    total:0,
    isLoading:true,
    machList:[],
    currentMach:{},
    machTypes:[],
    machParams:[],
    currentParam:{},
    paramInfo:{},
    // 能效分析，节能分析
    effInfo:{},
    // 拟合分析
    simulationInfo:{},
    tplList:[],
    selectedIds:[],
    userList:[],
    optional:{},
    runningInfo:[],
    machTreeData:[]
};

export default {
    namespace: 'mach',
    state: initialState,
    effects: {
        *fetchMachTypes(action, { call, put }){
            let { data, code } = yield call(getMachTypes);
            if ( code === 200 ) {
                yield put({ type:'getMachTypesResult', payload:{ data }})
            }
        },
        *fetchModelListByEnergy(action, { call, put, select }){
            // 能源类型（1：电；2：水；3：气；4:传感器；5：消防烟感可燃气体;6：空压站采集器
            let { resolve, reject, energyType } = action.payload || {};
            let { data, code, message } = yield call(getModelList, { energyType });
            if ( code === 200 ) {
                if ( resolve ) resolve(data);
            } else {
                if ( reject ) reject(message);
            }
        },
        *fetchMachList(action, { call, put, select }){
            let { user:{ companyId }, mach:{ optional }} = yield select();
            let { currentPage, pageSize  } = action.payload || {};
            // 请求终端采集设备的类型
            yield put.resolve({ type:'fetchMachTypes' });
            currentPage = currentPage || 1;
            pageSize = pageSize || 12;
            let params = { companyId, page:currentPage, pageSize:12 };
            Object.keys(optional).forEach(key=>{
                if ( optional[key] && optional[key] !== 'all' ) {
                    params[key] = decodeURI(optional[key]);
                }
            })
            console.log('fetch...');
            yield put({ type:'toggleLoading'});
            let { mach:{ machTypes }} = yield select();
            let { code, data, total } = yield call(getMachList, params);
            if ( code === 200 ) {
                yield put({ type:'getMachListResult', payload:{ data, machTypes, currentPage, total  }});
            }
        },
        *addMachAsync(action, { call, put, select }){
            let { user:{ companyId, companyName }} = yield select();
            let { resolve, reject, values, forEdit } = action.payload || {};
            let { data, code, message } = yield call( forEdit ? updateMach : addMach, { companyId, companyName, ...values });
            if ( code === 200 ){
                yield put({ type:'fetchMachList'});
                if ( resolve ) resolve();
            } else {
                if ( reject ) reject(message);
            }
        },
        *delMachAsync(action, { call, put, select }){
            let { resolve, reject, machId } = action.payload || {};
            let { data, code, message } = yield call(delMach, { payload:[machId] });
            if ( code === 200 ){
                yield put({ type:'fetchMachList'});
                if ( resolve ) resolve();
            } else {
                if ( reject ) reject(message);
            }
        },
        // 获取设备类型的指标参数
        *fetchMachParams(action, { call, put, select }){
            let { mach:{ currentMach }} = yield select();
            let { resolve, reject } = action.payload || {};
            if ( currentMach.machId || currentMach.key ) {
                let { data, code, message } = yield call(getMachParams, { energyType:currentMach.energyType || currentMach.key });
                if ( code === 200 ) {
                    yield put({ type:'getMachParamsResult', payload:{ data }});
                    if ( resolve ) resolve();
                } else {
                    if ( reject ) reject(message);
                }
            }
        },
        *fetchMachParamInfo(action, { call, put, select }){
            let { user:{ timeType, startDate, endDate }, mach:{ currentMach, currentParam }} = yield select();
            if ( currentMach.machId && currentParam.metricsId ) {
                let { data, code, message } = yield call(getMachParamInfo, { 
                    metricsId:currentParam.metricsId, 
                    registerCode:currentMach.registerCode, 
                    timeType, 
                    beginDate:startDate.format('YYYY-MM-DD'),
                    endDate:endDate.format('YYYY-MM-DD') 
                });
                if ( code === 200 ) {
                    yield put({ type:'getMachParamInfoResult', payload:{ data }})
                }
            }
        },
        *fetchMachEffInfo(action, { call, put, select, all }){
            let { user:{ timeType, startDate, endDate }, mach:{ currentMach, currentParam }} = yield select();
            if ( currentMach.machId && currentParam.metricsId ) {
                yield put({ type:'toggleLoading' });           
                let { data, code, message } = yield call(getMachEffInfo, { 
                    metricsId:currentParam.metricsId, 
                    registerCode:currentMach.registerCode, 
                    beginDate:startDate.format('YYYY-MM-DD'),
                    endDate:endDate.format('YYYY-MM-DD') 
                });
                if ( code === 200 ) {
                    yield put({ type:'getMachEffInfoResult', payload:{ data }})
                }
            }
        },
        *fetchMachSimulationInfo(action, { call, put, select }){
            let { user:{ companyId, timeType, startDate, endDate }} = yield select();
            let { data, code, message } = yield call(getMachSimulutionInfo, { companyId, timeType, beginDate:startDate.format('YYYY-MM-DD'), endDate:endDate.format('YYYY-MM-DD') });
            if ( code === 200 ) {
                yield put({ type:'getMachSimulutionInfoResult', payload:{ data }});
            }
        },
        // 设备运行报表
        *fetchRunningReport(action, { select, call, put }){
            let { user:{ timeType, startDate, endDate }, mach:{ machTypes, machTreeData, machList }} = yield select();
            // 构建设备类型的树状图
            let obj = machTreeData.filter(i=>i.key === 10)[0];
            yield put({ type:'setCurrentMach', payload:obj });
            yield put.resolve({ type:'fetchMachParams' });
            let { mach:{ machParams }} = yield select();
            let { code, data, message } = yield call(getCustomDate, { timeType, beginDate:startDate.format('YYYY-MM-DD'), endDate:endDate.format('YYYY-MM-DD'), value:30 });
            if ( code === 200 ) {
                yield put({ type:'getRunningReportResult', payload:{ data }});
            }
        }
    },
    reducers: {
        toggleLoading(state){
            return { ...state, isLoading:true };
        },
        getMachTypesResult(state, { payload:{ data }}) {
            let arr = [];
            if ( data ) {
                arr = Object.keys(data).map(key=>({ typeCode:key, typeName:data[key] })).sort((a,b)=>{ return a < b ? -1 : 1 })
            }
            return { ...state, machTypes:arr };
        },
        getMachListResult(state, { payload:{ data, machTypes, currentPage, total }}){
            let treeData = [];
            data.forEach(mach=>{
                let typeInfo = machTypes.filter(i=>i.typeCode === String(mach.energyType))[0] || {};
                let node = treeData.filter(i=>i.key === mach.energyType )[0];
                if ( ! node ) {
                    treeData.push({ key:mach.energyType, title:typeInfo.typeName, children:[{ key:mach.machId, title:mach.meterName }] }); 
                } else {
                    node.children.push({ key:mach.machId, meterName:mach.meterName, title:mach.meterName });
                }
            });
            return { ...state, machList:data, currentMach:data[0] || {}, machTreeData:treeData, currentPage, total, isLoading:false };
        },
        getMachParamsResult(state, { payload:{ data }}){
            return { ...state, machParams:data, currentParam:data[0] || {} };
        },
        getMachParamInfoResult(state, { payload:{ data }}){
            return { ...state, paramInfo:data };
        },
        getMachEffInfoResult(state, { payload:{ data }}){
            let { localMonthData, lastMonthData } = data;
            let infoList = [
                { title:'本月', children:[{ text:'最大值', value:localMonthData.maxV || 0, unit:'kw', subText:localMonthData.maxVDate  }, { text:'最小值', value:localMonthData.minV, unit:'kw', subText:localMonthData.minVDate }, { text:'平均值', value:localMonthData.avgV, unit:'kw' }] },
                { title:'上月', children:[{ text:'最大值', value:lastMonthData.maxV || 0, unit:'kw', subText:lastMonthData.maxVDate  }, { text:'最小值', value:lastMonthData.minV, unit:'kw', subText:lastMonthData.minVDate }, { text:'平均值', value:lastMonthData.avgV, unit:'kw' }] },
            ];
            data.infoList = infoList;
            return { ...state, effInfo:data };
        },
        getRunningReportResult(state, { payload:{ data }}){
            let machList = state.currentMach.children || [];
            let dateList = Object.keys(data);
            let runningInfo = { }, dataList = [];
            let columns = [
                { title:'序号', render:(text, record, index)=>{ return (state.currentPage - 1) * 12 + index + 1 }},
                { title:'设备名称', dataIndex:'title' }
            ];

            // 构建运行报表所需的Table组件数据结构
            // let [{
            //     meterName:'',
            //     id:'',
            //     dateList:['00:00', '01:00', ...],
            //     data:[[{ param1, value1 }, { param2, value2 }, ...]]
            // }]
            
            machList.forEach(mach=>{
                let obj = { ...mach, dataList:[] };
                dateList.forEach((date, index)=>{
                    // 构建表头
                    columns.push({
                        title:date,
                        children:state.machParams.map(i=>{
                            return {
                                title:`${i.metricsName}(${i.unitName})`,
                                dataIndex:'dataList',
                                render:(arr)=>{
                                    return arr[index][i.metricsCode];
                                }
                            }
                        })
                    })
                    // 构建Row数据
                    let paramInfo = {};
                    state.machParams.forEach(param=>{
                        param.value = 26 + Math.round(Math.random() * 10) ;
                        paramInfo[param.metricsCode] = param.value; 
                    });
                    obj.dataList.push(paramInfo);
                })
                dataList.push(obj);                       
            })
            runningInfo.columns = columns;
            runningInfo.tableData = dataList;
            console.log(runningInfo);
            return { ...state, runningInfo };
        },
        getMachSimulutionInfoResult(state, { payload:{ data }}){
            return { ...state, simulationInfo:data };
        },
        setOptional(state, { payload }){
            return { ...state, optional:payload };
        },
        setCurrentMach(state, { payload }){
            return { ...state, currentMach:payload };
        },
        setCurrentParam(state, { payload }){
            return { ...state, currentParam:payload };
        },
        reset(state){
            return initialState;
        }
    }
};
